import { CallServerInterceptor } from './CallServerInterceptor'
import { HttpDecorator } from './HttpDecorators'
import { Interceptor } from './Interceptor'
import { RealInterceptorChain } from './RealInterceptorChain'
import { Request } from './Request'
import { Response } from './Response'

export interface Call {
  getRequest(): Request

  execute(): Promise<Response>
}

export namespace Call {
  export interface Factory {
    newCall(request: Request): Call
  }
}

export class AxiosCall implements Call {
  constructor(public httpDecorator: HttpDecorator, private request: Request) {
  }

  execute(): Promise<Response> {

    return this.getResponseWithInterceptorChain()
  }

  getRequest(): Request {
    return this.request
  }

  private getResponseWithInterceptorChain(): Promise<Response> {
    const interceptors = new Array<Interceptor>()
    interceptors.push(...this.httpDecorator.interceptors)
    const chain = new RealInterceptorChain(this, interceptors, 0, this.request)


    interceptors.push(new CallServerInterceptor())

    const response = chain.proceed(this.request)

    return response
  }
}